package com.example.controller;

import com.example.model.Blog;
import com.example.model.User;
import com.example.service.BlogService;
import com.example.service.UserService;
import com.example.service.impl.BlogServiceImpl;
import com.example.service.impl.UserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.Date;
import java.util.List;

/**
 * 博客控制器
 */
@WebServlet("/blog/*")
public class BlogServlet extends HttpServlet {
    private BlogService blogService = new BlogServiceImpl();
    private UserService userService = new UserServiceImpl();
    
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException {
        String pathInfo = request.getPathInfo();
        if (pathInfo == null) {
            pathInfo = "/";
        }
        
        switch (pathInfo) {
            case "/":
            case "/list":
                listBlogs(request, response);
                break;
            case "/view":
                viewBlog(request, response);
                break;
            case "/new":
                showNewForm(request, response);
                break;
            case "/edit":
                showEditForm(request, response);
                break;
            case "/category":
                listBlogsByCategory(request, response);
                break;
            case "/search":
                searchBlogs(request, response);
                break;
            case "/myblogs":
                listMyBlogs(request, response);
                break;
            case "/hot":
                listHotBlogs(request, response);
                break;
            default:
                response.sendRedirect(request.getContextPath() + "/blog/list");
                break;
        }
    }
    
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException {
        String pathInfo = request.getPathInfo();
        if (pathInfo == null) {
            pathInfo = "/";
        }
        
        switch (pathInfo) {
            case "/create":
                createBlog(request, response);
                break;
            case "/update":
                updateBlog(request, response);
                break;
            case "/delete":
                deleteBlog(request, response);
                break;
            case "/search":
                searchBlogs(request, response);
                break;
            default:
                response.sendRedirect(request.getContextPath() + "/blog/list");
                break;
        }
    }
    
    /**
     * 显示所有博客列表
     */
    private void listBlogs(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException {
        List<Blog> blogList = blogService.getAllBlogs();
        request.setAttribute("blogList", blogList);
        
        // 获取热门博客
        List<Blog> hotBlogs = blogService.getHotBlogs(5);
        request.setAttribute("hotBlogs", hotBlogs);
        
        request.getRequestDispatcher("/WEB-INF/jsp/blog/list.jsp").forward(request, response);
    }
    
    /**
     * 查看博客详情
     */
    private void viewBlog(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException {
        String idStr = request.getParameter("id");
        if (idStr != null && !idStr.isEmpty()) {
            try {
                int id = Integer.parseInt(idStr);
                Blog blog = blogService.getBlogById(id);
                if (blog != null) {
                    // 增加阅读量
                    blogService.incrementViewCount(id);
                    // 重新获取更新后的博客
                    blog = blogService.getBlogById(id);
                    request.setAttribute("blog", blog);
                    
                    // 获取热门博客
                    List<Blog> hotBlogs = blogService.getHotBlogs(5);
                    request.setAttribute("hotBlogs", hotBlogs);
                    
                    request.getRequestDispatcher("/WEB-INF/jsp/blog/view.jsp").forward(request, response);
                    return;
                }
            } catch (NumberFormatException e) {
                // ID格式错误
            }
        }
        response.sendRedirect(request.getContextPath() + "/blog/list");
    }
    
    /**
     * 显示新建博客表单
     */
    private void showNewForm(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException {
        // 检查用户是否已登录
        HttpSession session = request.getSession(false);
        if (session == null || session.getAttribute("user") == null) {
            response.sendRedirect(request.getContextPath() + "/user/login");
            return;
        }
        
        request.getRequestDispatcher("/WEB-INF/jsp/blog/edit.jsp").forward(request, response);
    }
    
    /**
     * 创建新博客
     */
    private void createBlog(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException {
        // 检查用户是否已登录
        HttpSession session = request.getSession(false);
        if (session == null || session.getAttribute("user") == null) {
            response.sendRedirect(request.getContextPath() + "/user/login");
            return;
        }
        
        User user = (User) session.getAttribute("user");
        String title = request.getParameter("title");
        String content = request.getParameter("content");
        String category = request.getParameter("category");
        
        Blog blog = new Blog();
        blog.setTitle(title);
        blog.setContent(content);
        blog.setCategory(category);
        blog.setUserId(user.getId());
        blog.setAuthorName(user.getNickname() != null && !user.getNickname().isEmpty() ? 
                           user.getNickname() : user.getUsername());
        
        int blogId = blogService.createBlog(blog);
        if (blogId > 0) {
            response.sendRedirect(request.getContextPath() + "/blog/view?id=" + blogId);
        } else {
            request.setAttribute("error", "发布博客失败！");
            request.setAttribute("blog", blog);
            request.getRequestDispatcher("/WEB-INF/jsp/blog/edit.jsp").forward(request, response);
        }
    }
    
    /**
     * 显示编辑博客表单
     */
    private void showEditForm(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException {
        // 检查用户是否已登录
        HttpSession session = request.getSession(false);
        if (session == null || session.getAttribute("user") == null) {
            response.sendRedirect(request.getContextPath() + "/user/login");
            return;
        }
        
        User user = (User) session.getAttribute("user");
        String idStr = request.getParameter("id");
        if (idStr != null && !idStr.isEmpty()) {
            try {
                int id = Integer.parseInt(idStr);
                Blog blog = blogService.getBlogById(id);
                if (blog != null) {
                    // 检查是否是博客作者
                    if (blog.getUserId() != user.getId()) {
                        response.sendRedirect(request.getContextPath() + "/blog/list");
                        return;
                    }
                    
                    request.setAttribute("blog", blog);
                    request.getRequestDispatcher("/WEB-INF/jsp/blog/edit.jsp").forward(request, response);
                    return;
                }
            } catch (NumberFormatException e) {
                // ID格式错误
            }
        }
        response.sendRedirect(request.getContextPath() + "/blog/list");
    }
    
    /**
     * 更新博客
     */
    private void updateBlog(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException {
        // 检查用户是否已登录
        HttpSession session = request.getSession(false);
        if (session == null || session.getAttribute("user") == null) {
            response.sendRedirect(request.getContextPath() + "/user/login");
            return;
        }
        
        User user = (User) session.getAttribute("user");
        String idStr = request.getParameter("id");
        if (idStr != null && !idStr.isEmpty()) {
            try {
                int id = Integer.parseInt(idStr);
                Blog blog = blogService.getBlogById(id);
                if (blog != null) {
                    // 检查是否是博客作者
                    if (blog.getUserId() != user.getId()) {
                        response.sendRedirect(request.getContextPath() + "/blog/list");
                        return;
                    }
                    
                    blog.setTitle(request.getParameter("title"));
                    blog.setContent(request.getParameter("content"));
                    blog.setCategory(request.getParameter("category"));
                    
                    boolean success = blogService.updateBlog(blog);
                    if (success) {
                        response.sendRedirect(request.getContextPath() + "/blog/view?id=" + id);
                    } else {
                        request.setAttribute("error", "更新博客失败！");
                        request.setAttribute("blog", blog);
                        request.getRequestDispatcher("/WEB-INF/jsp/blog/edit.jsp").forward(request, response);
                    }
                    return;
                }
            } catch (NumberFormatException e) {
                // ID格式错误
            }
        }
        response.sendRedirect(request.getContextPath() + "/blog/list");
    }
    
    /**
     * 删除博客
     */
    private void deleteBlog(HttpServletRequest request, HttpServletResponse response) 
            throws IOException {
        // 检查用户是否已登录
        HttpSession session = request.getSession(false);
        if (session == null || session.getAttribute("user") == null) {
            response.sendRedirect(request.getContextPath() + "/user/login");
            return;
        }
        
        User user = (User) session.getAttribute("user");
        String idStr = request.getParameter("id");
        if (idStr != null && !idStr.isEmpty()) {
            try {
                int id = Integer.parseInt(idStr);
                Blog blog = blogService.getBlogById(id);
                if (blog != null && blog.getUserId() == user.getId()) {
                    blogService.deleteBlog(id);
                }
            } catch (NumberFormatException e) {
                // ID格式错误
            }
        }
        response.sendRedirect(request.getContextPath() + "/blog/myblogs");
    }
    
    /**
     * 按分类查询博客列表
     */
    private void listBlogsByCategory(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException {
        String category = request.getParameter("category");
        if (category != null && !category.isEmpty()) {
            List<Blog> blogList = blogService.getBlogsByCategory(category);
            request.setAttribute("blogList", blogList);
            request.setAttribute("category", category);
            
            // 获取热门博客
            List<Blog> hotBlogs = blogService.getHotBlogs(5);
            request.setAttribute("hotBlogs", hotBlogs);
            
            request.getRequestDispatcher("/WEB-INF/jsp/blog/category.jsp").forward(request, response);
        } else {
            response.sendRedirect(request.getContextPath() + "/blog/list");
        }
    }
    
    /**
     * 搜索博客
     */
    private void searchBlogs(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException {
        String keyword = request.getParameter("keyword");
        if (keyword != null && !keyword.isEmpty()) {
            List<Blog> blogList = blogService.searchBlogs(keyword);
            request.setAttribute("blogList", blogList);
            request.setAttribute("keyword", keyword);
            
            // 获取热门博客
            List<Blog> hotBlogs = blogService.getHotBlogs(5);
            request.setAttribute("hotBlogs", hotBlogs);
            
            request.getRequestDispatcher("/WEB-INF/jsp/blog/search.jsp").forward(request, response);
        } else {
            response.sendRedirect(request.getContextPath() + "/blog/list");
        }
    }
    
    /**
     * 查看用户自己的博客列表
     */
    private void listMyBlogs(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException {
        // 检查用户是否已登录
        HttpSession session = request.getSession(false);
        if (session == null || session.getAttribute("user") == null) {
            response.sendRedirect(request.getContextPath() + "/user/login");
            return;
        }
        
        User user = (User) session.getAttribute("user");
        List<Blog> blogList = blogService.getBlogsByUserId(user.getId());
        request.setAttribute("blogList", blogList);
        request.getRequestDispatcher("/WEB-INF/jsp/blog/myblogs.jsp").forward(request, response);
    }
    
    /**
     * 查看热门博客列表
     */
    private void listHotBlogs(HttpServletRequest request, HttpServletResponse response) 
            throws ServletException, IOException {
        List<Blog> blogList = blogService.getHotBlogs(10); // 获取前10篇热门博客
        request.setAttribute("blogList", blogList);
        request.getRequestDispatcher("/WEB-INF/jsp/blog/hot.jsp").forward(request, response);
    }
} 